package com.example.easyscript.service.master;

import com.example.easyscript.bean.task.TaskBean;
import com.example.easyscript.service.master.intf.MasterService;
import com.example.easyscript.service.master.intf.TaskManagerService;
import com.example.easyscript.service.master.intf.TaskRunnerService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Service

public class MasterServiceImpl implements MasterService,Runnable{

    @Resource
    private TaskManagerService managerService;

    @Resource
    private TaskRunnerService runnerService;

    private Boolean isRun = false;
    private long time = 3000;
    public final Boolean block = false;

    @Override
    @PostConstruct
    public void initContext() {
        managerService.initManager();
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void runMaster() {
        System.out.println("服务启动");
        isRun = true;
        synchronized (block){
            block.notifyAll();
        }
        System.out.println("唤醒所有线程");
    }

    @Override
    public void stopMaster() {
        isRun = false;
        System.out.println("服务停止");
    }

    @Override
    public void run() {
        //改线程是一个用来
        System.out.println("启动线程");
        //因为是一个系统所以它这个线程一定是死循环的
        while (true) {
            if (!isRun) {
                try {
                    synchronized (block){
                        System.out.println("线程阻塞");
                        block.wait();
                        System.out.println("动起来吧");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                //尝试拿一个任务出来
                TaskBean nextTask = managerService.getNextTask();
                System.out.println("获取任务" + nextTask.getTaskName());
                //执行任务
                runnerService.performTask(nextTask);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            try {
                if (isRun) {
                    Thread.sleep(time);
                } else {
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void testRun() {
        System.out.println("----------------------------运行开始--------------------\n");
        //获取任务
        TaskBean nextTask = null;
        try {
            nextTask = managerService.getNextTask();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //执行任务
        runnerService.performTask(nextTask);
        System.out.println("\n----------------------------运行结束--------------------");
    }
}
